package dev.spb3.handler;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {
    private static final String SECRET_KEY = "your_secretKey_key";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Authorization头信息
        String token = request.getHeader("Authorization");
        // 检查token是否存在并以“Bearer ”开头
        if(token != null && token.startsWith("Bearer ")) {
            // 去掉Bearer前缀
            token = token.substring(7);
            try {
                // 解析Token
                Claims claims = Jwts.parser()
                        .setSigningKey(SECRET_KEY)   // 设置用于验证前面的密钥
                        .parseClaimsJws(token)  // 解析JWT
                        .getBody(); // 获取JWT的负载部分
                // 将claims添加到请求属性中
                request.setAttribute("claims", claims);
            } catch (SignatureException e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT signature");
                return false;
            }

        }
        return true;
    }
}
